<?php
/**
 * +----------------------------------------------------------------------
 * | [ DO WHAT YOU LOVE AND FUCK THE REST ]
 * +----------------------------------------------------------------------
 * | EMAIL: < 931274989@qq.com >
 * +----------------------------------------------------------------------
 * | WECHAT: xzc016
 * +----------------------------------------------------------------------
 * | 管理员日志模型
 * +----------------------------------------------------------------------
 */
namespace app\admin\model;

use app\common\model\System;

use think\facade\Session;
use think\facade\Request;

class AdminLog extends Base
{
  //管理员日志记录
  public static function record()
  {
    $is_log = System::where('web','web')->value('is_log');
    // 日志开启
    if ($is_log == 1) {
      //入库信息
      $admin_id   = Session::get('admin.id',0);
      $username   = Session::get('admin.username','Unknown') ;
      $url        = Request::url();
      $title      = '';
      $content    = Request::except(['s','_pjax']); //s 变量为系统内置的变量，_pjax为js的变量，无记录的必要
      $ip         = Request::ip();
      $useragent  = Request::server('HTTP_USER_AGENT');
      $create_time = time();
      
      //标题处理
      $auth = new \Auth();
      $titleArr = $auth->getBreadCrumb();
      if (is_array($titleArr)) {
        foreach ($titleArr as $k => $v) {
          $title = '[' . $v['title'] . '] -> ' . $title;
        }
        $title = substr($title, 0, strlen($title) - 4);
      }
    
      //内容处理(过长的内容和涉及密码的内容不进行记录)
      if ($content) {
        foreach ($content as $k => $v) {
          if (is_string($v) && strlen($v) > 200 || stripos($k, 'password') !== false) {
            unset($content[$k]);
          }
        }
      }
    
      //登录处理
      if (strpos($url, 'Login/checkLogin') !== false) {
        $title = '[登录成功]';
        $content = '';
      }

      //插入数据
      if (!empty($title)) {
        self::create([
          'title'       => $title ? $title : '',
          'content'     => !is_scalar($content) ? json_encode($content) : $content,
          'url'         => $url,
          'admin_id'    => $admin_id,
          'username'    => $username,
          'useragent'   => $useragent,
          'ip'          => $ip,
          'create_time' => $create_time
        ]);
      }
    }
    else {
      return true;
    }
    
  }
}